package com.android.myj.view;

import java.util.List;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

import com.android.myj.R;
import com.android.myj.db.DataHelper;
import com.android.myj.model.User;
import com.android.utils.ImageUtil;
import com.tencent.weibo.api.User_API;
import com.tencent.weibo.beans.OAuth;
import com.tencent.weibo.utils.Configuration;
import com.tencent.weibo.utils.OAuthClient;
import com.tencent.weibo.utils.WeiBoConst;

/**
 * login activity 请首先修改beans/OAuth.
 * java里的oauth_consumer_key和oauth_consumer_secret为自己的key和secret
 * 
 * SDK根据网上代码改写而成 版权归所有参与者所有
 * 
 * @author hfahe
 */

public class Account extends ListActivity implements OnItemClickListener,
		OnItemLongClickListener, OnClickListener {

	private ImageView user_default_headicon;
	private LinearLayout account_add_btn_bar;
	private User currentUser;
	public static final String appName = "QWeibo4Android";
	public static OAuth oauth;
	public static OAuthClient auth;

	private DataHelper dataHelper;

	private List<User> userList;

	private UserAdapater adapater;
	private ListView listView;

	SharedPreferences preferences;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.account);
		setUpViews();// 设置view
		setUpListeners();// 设置listenter
		userList();
	}

	private void userList() {
		dataHelper = DataHelper.getInstance(getApplicationContext());// 获取数据库连接类，用了单例，保证全局只有一个此对象。
		userList = dataHelper.GetUserList(false);
		preferences = getSharedPreferences("default_user",
				Activity.MODE_PRIVATE);
		String nick = preferences.getString("user_default_nick", "");// 取得微博默认登录账号信息

		User user = null;

		if (userList != null && userList.size() > 0) {
			if (nick != "") {
				user = DataHelper.getUserByName(nick, userList);// 取得微博默认登录账号信息
			}
			if (user == null) {
				user = userList.get(0);
			}
		}
		if (user != null) {
			user_default_headicon.setImageDrawable(user.getUserIcon());
			currentUser = user;
		} else {
			user_default_headicon.setImageDrawable(null);
		}

		if (userList != null && userList.size() > 0) {
			adapater = new UserAdapater();
			adapater.notifyDataSetChanged();
			listView.setAdapter(adapater);
			listView.setOnItemClickListener(this);
		}
	}

	private void setUpViews() {
		listView = getListView();
		user_default_headicon = (ImageView) findViewById(R.id.user_default_headicon);
		account_add_btn_bar = (LinearLayout) findViewById(R.id.account_add_btn_bar);
	}

	private void setUpListeners() {
		user_default_headicon.setOnClickListener(this);
		account_add_btn_bar.setOnClickListener(this);
		listView.setOnItemLongClickListener(this);
	}

	class UserAdapater extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return userList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return userList.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			UserHolder userHolder = new UserHolder();
			if (convertView == null) {
				convertView = LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.user_list_item, null);
			}
			userHolder.user_headicon = (ImageView) convertView
					.findViewById(R.id.user_headicon);
			userHolder.user_nick = (TextView) convertView
					.findViewById(R.id.user_nick);
			userHolder.user_name = (TextView) convertView
					.findViewById(R.id.user_name);
			userHolder.user = userList.get(position);
			try {
				userHolder.user_headicon.setImageDrawable(userHolder.user
						.getUserIcon());
				userHolder.user_nick.setText(userHolder.user.getUserName());
				userHolder.user_name.setText("@" + userHolder.user.getUserId());
			} catch (Exception e) {
				e.printStackTrace();
			}
			return convertView;
		}

	}

	static class UserHolder {
		ImageView user_headicon;
		TextView user_nick;
		TextView user_name;
		User user;
	}

	@Override
	public void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		final Uri uri = intent.getData();
		if (uri != null) {
			String oauth_verifier = uri.getQueryParameter("oauth_verifier");
			String oauth_token = uri.getQueryParameter("oauth_token");
			getToken(oauth_verifier, oauth_token);
			userList();
		}
	}

	public void getToken(String oauth_verifier, String oauth_token) {
		oauth.setOauth_verifier(oauth_verifier);
		oauth.setOauth_token(oauth_token);

		try {
			oauth = auth.accessToken(oauth);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if (oauth.getStatus() == 2) {
			System.out.println("Get Access Token failed!");
			return;
		} else {
			try {
				User_API api = new User_API();
				String info = api.info(oauth,
						WeiBoConst.ResultType.ResultType_Json);
				JSONObject data = new JSONObject(info).getJSONObject("data");
				String headUrl = null;
				if (data.getString("head") != null
						&& !"".equals(data.getString("head"))) {
					headUrl = data.getString("head") + "/100";
				}
				String userId = data.getString("name");
				String userName = data.getString("nick");

				User user = new User();// 生成一个user对象保存到数据库
				user.setUserId(userId);
				user.setUserName(userName);
				user.setToken(oauth.getOauth_token());
				user.setTokenSecret(oauth.getOauth_token_secret());
				if (dataHelper.HaveUserInfo(userId)) {// 数据库已经存在了此用户
					dataHelper.UpdateUserInfo(userName, ImageUtil
							.getRoundBitmapFromUrl(headUrl, 15), userId);
				} else {
					if (headUrl == null) {
						headUrl = Configuration.defaultHeadUrl;
					}
					dataHelper.SaveUserInfo(user, ImageUtil
							.getRoundBitmapFromUrl(headUrl, 15));
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		currentUser = userList.get(position);
		user_default_headicon.setImageDrawable(currentUser.getUserIcon());

	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			final int position, long id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(Account.this);
		CharSequence[] items = new CharSequence[] { "删除账号", "取消" };
		builder.setItems(items, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case 0:
					String userId = userList.get(position).getUserId();
					dataHelper.DelUserInfo(userId);
					Editor editor = preferences.edit();
					if (preferences.getString("user_default_name", "").equals(
							userId)) {
						editor.putString("user_default_nick", "");
						editor.putString("user_default_name", "");
						editor.commit();// 清除里面保存的记录SharedPreferences
					}
					userList();
					break;
				}
			}
		}).show();
		return false;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.account_add_btn_bar:
			try {
				oauth = new OAuth();
				auth = new OAuthClient();// OAuth 认证对象
				// 获取request token
				oauth = auth.requestToken(oauth);
				String oauth_token = oauth.getOauth_token();
				String url = OAuth.AUTHORIZE_URL + oauth_token;
				Uri uri = Uri.parse(url);
				startActivity(new Intent(Intent.ACTION_VIEW, uri));
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case R.id.user_default_headicon: {
			preferences = getSharedPreferences("default_user",
					Activity.MODE_PRIVATE);
			Editor editor = preferences.edit();
			editor.putString("user_default_nick", currentUser.getUserName());
			editor.putString("user_default_name", currentUser.getUserId());
			editor.commit();
			Intent intent = new Intent(Account.this, Main.class);
			startActivity(intent);
			finish();
		}
			break;
		}

	}
}